
from applications.extensions.init_apscheduler import scheduler
from applications.common.hangingUpCore.execution_logic import ExecutionLogic


'''
    挂机流程(主要处理定时任务)
'''
class ExecutionFlow:
    
    def __init__(self):
        self.setAttribute(dict(),dict())
        pass

    '''
        挂机流程初始化
    '''
    def initTask(self,baseParam,opertionParam):
        # 属性初始化
        self.setAttribute(baseParam,opertionParam)
        # 检测定时任务是否存在,进行复写
        self.checkTaskExesit()
    
    '''
        baseParam : 执行基本流程属性
        opertionParam : 操作逻辑所需属性
    '''
    def setAttribute(self,baseParam,opertionParam):
        # 操作属性值
        # self.opertionParam = opertionParam
        # 维持一个执行逻辑依赖
        self.executionLogic = ExecutionLogic()
        self.executionLogic.setAttribute(opertionParam)

        ## 定时任务基本属性值 
        self.taskId = 'EXECUTION_FLOW_TASK_ID'
        self.taskName = 'EXECUTION_FLOW_TASK'
        self.taskType = 'interval'
        # 设置定时任务时间,如果未传则默认一秒检测一次;
        self.intervalSeconds = baseParam.get('intervalSeconds') if 'intervalSeconds' in baseParam else 1 
        #是否覆盖之前的定时任务设置 ,默认为False
        self.replaceTask= baseParam.get('replaceTask') if 'replaceTask' in baseParam else False
        # self.pictureUrl = paramDic.pictureUrl if paramDic.has_key('pictureUrl') else None

    '''
        定时检测当前执行步骤，执行下一步操作
    '''
    def scheduledTaskDetection(self):
        print('开始执行定时任务:' + self.taskId)
        pass
        # 执行完毕则停止定时任务
        if(self.executionLogic.stateInfo['finish']) : 
            self.stopScheduledTask()
        # 执行中则退出
        if(self.executionLogic.stateInfo['runing']) :
            return
        # 执行逻辑
        self.executionLogic.executeExecution()
        pass


    '''
        检测定时任务是否存在,如果不存在则先创建定时任务
    '''
    def checkTaskExesit(self):
        print(str(type(scheduler.get_job(self.taskId))) + ":  " + str(scheduler.get_job(self.taskId)) )
        if scheduler.get_job(self.taskId) is not None and not self.replaceTask:   
            scheduler.resume_job(self.taskId)
        else :
            scheduler.add_job(
                func=self.scheduledTaskDetection,
                id=self.taskId,
                name=self.taskName,
                # args=(self.opertionParam),
                args=(),
                trigger=self.taskType,
                seconds=self.intervalSeconds,
                replace_existing=True
            )
    '''
        停止定时任务
    '''
    def stopScheduledTask(self):
        scheduler.pause_job(self.taskId)

    '''
        开始定时任务
    '''
    def startScheduledTask(self):
        scheduler.resume_job(self.taskId)


    '''
        删除任务
    '''
    def removeScheduledTask(self):
        scheduler.remove_job(self.taskId)

    

    